const fs = require("fs");
const path = require('path');
const { exec } = require('child_process');
const postcss = require("postcss");
const postcssScss = require("postcss-scss");

const args = process.argv;
const filePath = args[2];

// const inputFile = "src/pages/others/home/index.scss";
const inputFile = path.resolve(filePath);
// const inputFile = "src/components/coupon-item/index.scss";
const scssContent = fs.readFileSync(inputFile, "utf8");

const targetProps = [
  "display:flex",
  "align-items:center",
  "flex-direction:column",
  "justify-content:center",
  "justify-content:space-between",
  "justify-content:space-around",
  "justify-content:flex-end",
  "align-items:flex-end",
  "align-items:flex-start",
  "align-items:center",
  // 可以继续添加其他属性
].map(prop => prop.replace(/\s+/g, "")); // 移除所有空格，确保匹配

function areArraysEqual(arr1, arr2) {
  // 如果两个数组长度不同，直接返回false
  if (arr1.length !== arr2.length) {
    return false;
  }

  // 创建一个对象来记录第一个数组中每个元素的出现次数
  const elementCounts = {};

  // 统计第一个数组的元素
  for (const element of arr1) {
    elementCounts[element] = (elementCounts[element] || 0) + 1;
  }

  // 检查第二个数组的元素
  for (const element of arr2) {
    // 如果元素不存在或计数为0，返回false
    if (!elementCounts[element]) {
      return false;
    }
    elementCounts[element]--;
  }

  return true;
}

const clssNameNum = {
  // "display:flex": "flex_row",
  "display:flex,flex-direction:column": "flex_col",

  "display:flex,justify-content:center": "row_start_center",
  "display:flex,justify-content:space-between": "row_start_between",
  "display:flex,justify-content:space-around": "row_start_around",
  "display:flex,justify-content:flex-end": "row_start_end",

  "display:flex,align-items:center": "row_center_start",
  "display:flex,align-items:center,justify-content:space-between": "row_center_between",
  "display:flex,align-items:center,justify-content:space-around": "row_center_around",
  "display:flex,align-items:center,justify-content:flex-end": "row_center_end",

  "display:flex,align-items:flex-end": "row_end_start",
  "display:flex,align-items:flex-end,justify-content:space-between": "row_end_between",
  "display:flex,align-items:flex-end,justify-content:space-around": "row_end_around",
  "display:flex,align-items:flex-end,justify-content:center": "row_end_center",

  "display:flex,justify-content:center,align-items:center": "row_cc",

  "display:flex,flex-direction:column,justify-content:center": "col_start_center",
  "display:flex,flex-direction:column,justify-content:space-between": "col_start_between",
  "display:flex,flex-direction:column,justify-content:space-around": "col_start_around",
  "display:flex,flex-direction:column,justify-content:flex-end": "col_start_end",

  "display:flex,flex-direction:column,align-items:center": "col_center_start",
  "display:flex,flex-direction:column,align-items:center,justify-content:space-between": "col_center_between",
  "display:flex,flex-direction:column,align-items:center,justify-content:space-around": "col_center_around",
  "display:flex,flex-direction:column,align-items:center,justify-content:flex-end": "col_center_end",

  "display:flex,flex-direction:column,align-items:flex-end": "col_end_start",
  "display:flex,flex-direction:column,align-items:flex-end,justify-content:space-between": "col_end_between",
  "display:flex,flex-direction:column,align-items:flex-end,justify-content:space-around": "col_end_around",
  "display:flex,flex-direction:column,align-items:flex-end,justify-content:center": "col_end_center",

  "display:flex,flex-direction:column,justify-content:center,align-items:center": "col_cc",
}

function main() {
  const result = postcss().process(scssContent, { syntax: postcssScss, from: undefined });
  const removedLog = {};

  result.root.walkRules(rule => {
    function getFullSelector(rule_) {
      let selector = rule_.selector;
      let parent = rule_.parent;
      while (parent && parent.type === 'rule') {
        // 替换&为父选择器
        selector = selector.replace(/&/g, parent.selector);
        parent = parent.parent;
      }

      if (!selector.includes('.') || selector.includes(':') || selector.includes('>') || selector.includes('~') || selector.includes('+')) {
        return
      }

      if (selector.includes(',')) {
        selector = selector.split(',');
        return selector.filter(item => item.includes('.')).map(item => item.split('.')[1])
      }

      return [selector.split('.')[1]];
    };

    const selector = getFullSelector(rule);
    const newProps = [];
    const removeList = [];

    if (!selector) {
      return
    }

    rule.walkDecls(decl => {
      const normalizedDecl = `${decl.prop}:${decl.value}`.replace(/\s+/g, '');
      // 精确匹配（属性名+值完全一致）
      if (targetProps.includes(normalizedDecl) && decl.parent === rule) {
        removeList.push(decl.remove.bind(decl));
        newProps.push(normalizedDecl);
        // 记录被删除的属性
        // if (!removedLog[selector]) {
        //   removedLog[selector] = [];
        // }
        // removedLog[selector].push({
        //   property: decl.prop,
        //   value: decl.value,
        //   line: decl.source?.start?.line, // 源代码行号
        // });
      };
    });

    const isMatch = Object.keys(clssNameNum).some((v) => {
      const k = areArraysEqual(newProps, v.split(','));
      if (k) {
        selector.forEach(s => removedLog[s] = clssNameNum[v])
        removeList.forEach(fn => fn());
        return true;
      };
    });

    if (!isMatch) {
      delete removedLog[selector];
    };
  });

  console.log('结果：', removedLog);
  fs.writeFileSync(inputFile, result.css, "utf8");
};

main();